﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GeoLocationServiceProxies.GeocodeService;

namespace Locator.GeoLocation.Services
{
    public class GeoLocationServiceAgent : IGeoLocationServiceAgent
    {
        private readonly IGeocodeServiceProxy proxy;

        /// <summary>
        /// Initializes a new instance of the GeoLocationServiceAgent class.
        /// </summary>
        public GeoLocationServiceAgent()
        {
            this.proxy = new GeocodeServiceProxy();
        }

        public GeoLocation.BusinessEntities.Location GeoLocate(GeoLocation.BusinessEntities.Address address)
        {
            GeoLocation.BusinessEntities.Location result = new GeoLocation.BusinessEntities.Location();
            GeocodeRequest innerRequest = new GeocodeRequest();
            innerRequest.Address = new Address()
            {
                AddressLine = address.AddressLine,
                AdminDistrict = address.AdminDistrict,
                CountryRegion = address.CountryRegion,
                District = address.District,
                FormattedAddress = address.FormattedAddress,
                Locality = address.Locality,
                PostalCode = address.PostalCode,
                PostalTown = address.PostalTown
            };

            GeocodeRequest1 request = new GeocodeRequest1(innerRequest);
            GeocodeResponse1 response = this.proxy.Geocode(request);
            GeocodeResponse innerResponse = response.GeocodeResult;
            if (innerResponse.Results != null
                && innerResponse.Results.Count > 0
                && innerResponse.Results[0].Locations != null 
                && innerResponse.Results[0].Locations.Count > 0)
            {
                result.Latitude = (decimal)innerResponse.Results[0].Locations[0].Latitude;
                result.Longitude = (decimal)innerResponse.Results[0].Locations[0].Longitude;
            }

            return result;
        }
    }
}
